package com.skyable.auth.config.security.service;

import com.skyable.auth.entity.SysPermission;
import com.skyable.auth.entity.SysUser;
import com.skyable.auth.service.IPermissionService;
import com.skyable.auth.service.IUserService;
import com.skyable.common.common.ServiceResult;
import com.skyable.common.constants.exception.AuthExcpConstants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @author GaoYuan
 * @title: UserDetailServiceImpl
 * @projectName spring-cloud-demo
 * @description: TODO
 * @date 2021/4/213:10
 */
@Service
public class UserDetailServiceImpl implements UserDetailsService {

    @Autowired
    private IUserService userService;
    @Autowired
    private IPermissionService permissionService;

    @Override
    public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException {
        //获取本地用户
        ServiceResult<SysUser> userServiceResult = userService.getUserByUserName(userName);
        if(!userServiceResult.getSuccess()) {
            throw new UsernameNotFoundException(AuthExcpConstants.ERROR_MSG_USER_NOT_EXISTS);
        }
        SysUser sysUser = userServiceResult.getResult();
        if(sysUser != null){
            List<GrantedAuthority> authorityList = new ArrayList<>();
            //查询用户权限
            ServiceResult<List<SysPermission>> permissionServiceResult = permissionService.findPermissionByUserName(userName);
            if(permissionServiceResult.getSuccess()) {
                List<SysPermission> sysPermissionList = permissionServiceResult.getResult();
                for(SysPermission sysPermission : sysPermissionList) {
                    authorityList.add(new SimpleGrantedAuthority(sysPermission.getPermissionCode()));
                }
            }
            //返回oauth2的用户
            return new org.springframework.security.core.userdetails.User(
                    sysUser.getUsername(),
                    sysUser.getPassword(),
                    authorityList) ;
        }else{
            throw new UsernameNotFoundException(AuthExcpConstants.ERROR_MSG_USER_NOT_EXISTS);
        }
    }
}
